/*
 * Main.c
 *
 *  Created on: 16 juli 2021
 *      Author: Daniel Mårtensson
 */

#include <stdio.h>

/* Include Open SAE J1939 */
#include "Open_SAE_J1939/Open_SAE_J1939.h"

/* Include ISO 11783 */
#include "ISO_11783/ISO_11783-7_Application_Layer/Application_Layer.h"

int main() {

	/* Create our J1939 structure with two ECU */
	J1939 j1939_1 = {0};
	J1939 j1939_2 = {0};

	/* Important to sent all non-address to 0xFF - Else we cannot use ECU address 0x0 */
	uint8_t i;
	for(i = 0; i < 255; i++){
		j1939_1.other_ECU_address[i] = 0xFF;
		j1939_2.other_ECU_address[i] = 0xFF;
	}

	/* Set the ECU address */
	j1939_1.information_this_ECU.this_ECU_address = 0x80;												/* From 0 to 253 because 254 = error address and 255 = broadcast address */
	j1939_2.information_this_ECU.this_ECU_address = 0x7A;

	/* Set the information about valve 1 for ECU 2 */
	j1939_2.this_general_purpose_valve_estimated_flow.extend_estimated_flow_standard = 150;
	j1939_2.this_general_purpose_valve_estimated_flow.fail_safe_mode = FAIL_SAFE_MODE_ACTIVATED;	/* Jump to neutral because now the valve is in fail safe mode */
	j1939_2.this_general_purpose_valve_estimated_flow.limit = LIMIT_NOT_USED;
	j1939_2.this_general_purpose_valve_estimated_flow.retract_estimated_flow_standard = 50;
	j1939_2.this_general_purpose_valve_estimated_flow.valve_state = VALVE_STATE_INITIALISATION;
	j1939_2.this_general_purpose_valve_estimated_flow.retract_estimated_flow_extended = 1000;
	j1939_2.this_general_purpose_valve_estimated_flow.extend_estimated_flow_extended = 65535;

	/* Send a request from ECU 1 to ECU 2 */
	ISO_11783_Send_Request_General_Purpose_Valve_Estimated_Flow(&j1939_1, 0x7A);

	/* Read the request for ECU 2*/
	Open_SAE_J1939_Listen_For_Messages(&j1939_2);

	/* Read the response request for ECU 1 */
	Open_SAE_J1939_Listen_For_Messages(&j1939_1);

	/* Display what we got */
	printf("Extend estimated flow standard = %i\nFail safe mode = %i\nLimit = %i\nRetract estimated flow standard = %i\nValve state = %i\nRetract estimated flow extended = %i\nExtend estimated flow extended = %i\nFrom ECU address = 0x%X"
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.extend_estimated_flow_standard
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.fail_safe_mode
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.limit
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.retract_estimated_flow_standard
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.valve_state
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.retract_estimated_flow_extended
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.extend_estimated_flow_extended
			,j1939_1.from_other_ecu_general_purpose_valve_estimated_flow.from_ecu_address);

	return 0;
}
